<template>
  <view class="ui-swiper">
    <swiper
      :current="state.cur"
      :circular="props.data.circular"
      :autoplay="props.data.autoplay"
      :interval="props.data.interval"
      :duration="props.data.duration"
      :indicator-dots="props.data.dots"
      :indicator-color="props.data.color"
      :indicator-active-color="props.data.activeColor"
      :style="customStyle"
      @change="swiperChange"
    >
      <swiper-item
        class="swiper-item ss-flex"
        v-for="(item, index) in state.dataList"
        :key="props.data.type + index"
        @tap="sheep.$router.go('/pages/news/news-detail', { id: item.id })"
      >
        <image :src="sheep.$url.cdn(item.cover)" class="news-img" mode="scaleToFill" />
        <view class="news-content ss-flex-1 ss-flex-col ss-row-between">
          <view class="news-title ss-line-2">{{ item.title }}</view>
          <view class="news-time">{{ item.createtime }}</view>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
import { computed, reactive, onMounted } from "vue";
import sheep from "@/sheep";

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  styles: {
    type: Object,
    default: () => ({}),
  },
});

onMounted(() => {
  getList();
})

const state = reactive({
  imgHeight: 0, // 默认高度
  cur: 0, // 当前轮播图索引
  queryParams: {},
  dataList: [], // 轮播图数据
});

// 自动计算高度
const customStyle = computed(() => {
  let height;
  // 固定高度情况
  if (props.data.height != 0) {
    height = props.data.height;
  } else {
    // 图片预加载占位高度
    if (state.imgHeight != 0) {
      height = state.imgHeight;
    }
  }
  return {
    height: height + "rpx",
  };
});

// 计算轮播图片最大高度
function onImgLoad(e) {
  if (props.data.height == 0) {
    let newHeight = (e.detail.height / e.detail.width) * 750;
    if (state.imgHeight < newHeight) {
      state.imgHeight = newHeight;
    }
  }
}

// 获取轮播图数据
const getList = () => {
  let type = props.data.title;
  sheep.$api.news.homeNews().then((res) => {
    if (res.code == 1) {
      state.dataList = res.data[type];
      console.log(type, ':::', state.dataList);
    }
  });
};

// current 改变时会触发 change 事件
const swiperChange = (e) => {
  if (e.detail.source !== "touch" && e.detail.source !== "autoplay") return;
  state.cur = e.detail.current;
};
</script>

<style lang="scss" scoped>
.ui-swiper {
  .swiper-item {
    background-color: #fff;
    padding: 18rpx 20rpx;
    margin-bottom: 20rpx;
    box-sizing: border-box;
    .news-img {
      width: 136rpx;
      height: 136rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }
    .news-content {
      font-size: 24rpx;
      height: 136rpx;
      .news-title {
        color: #555;
        line-height: 40rpx;
      }
      .news-time {
        color: #979797;
      }
    }
  }
}
</style>
